<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item el-form-item label="流程名称" prop="flowName">
        <el-input
          v-model="queryParams.flowName"
          placeholder="请输入流程名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="流程状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择">
          <el-option
            v-for="item in flowStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="申请时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      :data="flowInstList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        label="流程名"
        align="center"
        key="flowInst.name"
        prop="flowInst.name"
        v-if="columns[0].visible"
      />
      <el-table-column
        label="流程状态"
        align="center"
        key="flowInst.status"
        prop="flowInst.status"
        v-if="columns[1].visible"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span style="color: orange" v-if="scope.row.flowInst.status == 0">进行中</span>
          <span style="color: #67c23a" v-if="scope.row.flowInst.status == 1">成功</span>
          <span style="color: red" v-if="scope.row.flowInst.status == 2">失败</span>
          <span style="color: grey" v-if="scope.row.flowInst.status == 3"
            >退回，待修改</span
          >
        </template>
      </el-table-column>
      <el-table-column
        label="申请者名称"
        align="center"
        key="userName"
        prop="userName"
        v-if="columns[2].visible"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="申请者昵称"
        align="center"
        key="nickName"
        prop="nickName"
        v-if="columns[7].visible"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="所属部门"
        align="center"
        key="deptName"
        prop="deptName"
        v-if="columns[3].visible"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="申请时间"
        align="center"
        prop="createTime"
        v-if="columns[4].visible"
        width="160"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.flowInst.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-link
            :underline="false"
            class="el-icon-view"
            @click="detail(scope.row)"
            >详情</el-link
          >&nbsp;
          <el-link
            :underline="false"
            class="el-icon-edit"
            v-if="scope.row.flowInst.status == 0"
            @click="handleExamine(scope.row)"
            >审批</el-link
          >&nbsp;
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 流程详情对话框 -->
    <el-dialog
      title="流程详情"
      :visible.sync="detailDialog"
      :before-close="closeDetail"
    >
      <el-form :model="flowInst" label-position="right" label-width="80px">
        <el-form-item label="流程名称">
          <el-input
            :disabled="true"
            v-model="flowInst.name"
            autocomplete="off"
            style="width: 30%"
          />
        </el-form-item>
        <el-form-item label="申请时间">
          <el-input
            :disabled="true"
            v-model="flowInst.createTime"
            autocomplete="off"
            style="width: 30%"
          />
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
      <el-form :model="flowInst" label-position="right" label-width="100px">
        <div v-for="(item, index) in flowNodeInst" :key="(item, index)">
          <el-form-item label="节点名称">
            <el-input
              :disabled="true"
              v-model="item.name"
              autocomplete="off"
              style="width: 30%"
            />
          </el-form-item>
          <el-form-item label="节点状态">
            <span v-if="item.status == 0" style="color: grey">未开始</span>
            <span v-if="item.status == 1" style="color: orange">审核中</span>
            <span v-if="item.status == 2" style="color: green">通过</span>
            <span v-if="item.status == 3" style="color: red">终止</span>
            <span v-if="item.status == 4" style="color: black">回退</span>
          </el-form-item>
          <el-form-item label="审核人用户名">
            <el-input
              :disabled="true"
              v-model="item.relatedUserName"
              autocomplete="off"
              style="width: 30%"
            />
          </el-form-item>
          <el-form-item label="审核人昵称">
            <el-input
              :disabled="true"
              v-model="item.relatedUserNickName"
              autocomplete="off"
              style="width: 30%"
            />
          </el-form-item>
          <el-form-item label="审核时间">
            <el-input
              :disabled="true"
              v-model="item.time"
              autocomplete="off"
              style="width: 30%"
            />
          </el-form-item>
          <el-form-item label="审核ip">
            <el-input
              :disabled="true"
              v-model="item.ip"
              autocomplete="off"
              style="width: 30%"
            />
          </el-form-item>
          <el-form-item label="审核意见">
            <el-input
              :disabled="true"
              v-model="item.idea"
              autocomplete="off"
              style="width: 80%"
            />
          </el-form-item>
          <el-form-item label="审核签名">
            <img :src="item.sign" alt="" class="ca-img">
          </el-form-item>
          <el-divider></el-divider>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDetail" type="primary">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 审批流程对话框 -->
    <el-dialog
      title="流程审批"
      :before-close="cancelExamine"
      :visible.sync="examineDialog"
    >
      <div>
        <h1>{{ formInfo.formName }}</h1>
        <el-form label-position="top" label-width="80px">
          <div v-for="(item, index) in answers" :key="(item, index)">
            <el-form-item
              :label="index + 1 + '、' + questions[index].questionName"
            >
              <div v-if="questions[index].questionType == 0">
                <el-input v-model="item.answer" type="textarea" :disabled="true"></el-input>
              </div>
            </el-form-item>
          </div>
            <el-form-item
              label="审批意见"
            >
                <el-input v-model="nodeInst.idea" type="textarea"></el-input>
            </el-form-item>
            <el-form-item
              label="电子签名"
            >
            <vue-esign ref="esign" :width="300" :height="150" :isCrop="true"  />
                <el-button @click="handleReset" size="mini">清空画板</el-button>
            </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelExamine()">取 消</el-button>
        <el-button type="info" @click="submitExamine(3)">回退</el-button>
        <el-button type="danger" @click="submitExamine(2)">终止</el-button>
        <el-button type="primary" @click="submitExamine(0)">审批</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { nanoid } from "nanoid";
import { listDept } from "@/api/system/dept";
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
} from "@/api/system/user";
import { listFlowInst } from "@/api/flow/myapply";
import { getFlowInstDetail ,getFormInfo,getFlowAnswer,opFlowInst} from "@/api/flow/waittodo";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: { Treeselect },
  data() {
    return {
      //流程详情对话框
      detailDialog: false,
      //流程实例详情
      flowInst: {},
      flowNodeInst: [],
      //审批
      examineDialog:false,
      formInfo:{},
      questions:[],
      answers:[],
      nodeInst:{},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 审核节点用户数据
      userList: [],
      //流程数据列表
      flowInstList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      flowDialogVis: false,
      //是否显示抽屉
      drawerVis: false,
      //搜索表单的部门id
      drawer: { deptId: null, formList: [] },
      // 部门名称
      deptName: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      //正在审批的流程信息
      flowInfo: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        currentUserId: this.$store.state.user.id,
        flowName: undefined,
        status: undefined,
      },
      flowStatus: [
        { value: 0, label: "进行中" },
        { value: 1, label: "成功" },
        { value: 2, label: "失败" },
        { value: 3, label: "回退，待修改" },
      ],
      // 列信息
      columns: [
        { key: 0, label: `流程名`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `流程标识`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `申请时间`, visible: true },
        { key: 7, label: `申请者昵称`, visible: true },
      ],
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    console.log(this.$store.state.user.token);
    this.getList();
  },
  methods: {
    //电子签名
    handleReset () {
        this.$refs['esign'].reset() //清空画布
    },
    handleGenerate () {
        this.$refs['esign'].generate().then(res => {
        this.nodeInst.sign = res // 得到了签字生成的base64图片
        }).catch(err => { //  没有签名，点击生成图片时调用
        this.$message({
            message: err + '您尚未签名',
            type: 'warning'
        });
        })
    },
    /** 查询流程列表 */
    getList() {
      this.loading = true;
      listFlowInst(this.addDateRange1(this.queryParams, this.dateRange)).then(
        (response) => {
          console.log("待审批列表");
          console.log(response);
          this.flowInstList = response.flowInfoInst;
          console.log(this.flowInstList);
          this.total = response.counts;
          this.loading = false;
        }
      );
    },
    detail(row) {
      // var params1 = {
      //     formId: row.formId,
      //     flowInstId: row.id,
      // };
      // //获取表单信息、题目、答案
      // getFlowForm(params1).then((response) => {
      //     console.log(response);
      // });
      var params2 = {
        flowInstId: row.flowInst.id,
      };
      //获取流程及其节点信息
      getFlowInstDetail(params2).then((response) => {
        console.log(response);
        this.flowInst = response.data.flowInst;
        this.flowNodeInst = response.data.flowNodeInst;
        this.detailDialog = true;
      });
    },
    //关闭详情
    closeDetail() {
      this.resetDetail();
      this.detailDialog = false;
    },
    //重置详情
    resetDetail() {
      this.flowInst = {};
      this.flowNodeInst = [];
    },
    //打开审批对话框
    handleExamine(row){
        console.log("正在审批的流程");
        console.log(row);
        //存储流程信息
        this.flowInfo=row.flowInst;
        console.log(this.flowInfo);
      //创建审批节点信息
      this.nodeInst={
        idea:'',
        sign:'',
        time:'',
        ip:process.env.BASE_IP
      };
      console.log(this.nodeInst);
      //获取业务表单基本信息、问题，创建答案数组
      var params1 = {
        formId: row.flowInst.formId,
      };
      getFormInfo(params1).then((response) => {
        console.log("response");
        console.log(response);
        this.formInfo = response.data.form;
        this.questions = response.data.questionList;
        for (var i = 0; i < this.questions.length; i++) {
          var params2={
            questionType:this.questions[i].questionType,
            questionId:this.questions[i].id,
            flowInstId:row.flowInst.id
          };
        getFlowAnswer(params2).then((response) => {
            console.log(response);
            this.answers.push(response.answer);
        });
        }
      });
      this.examineDialog = true;
    },
    //取消审批
    cancelExamine(){
        this.resetExamine();
        this.examineDialog=false;
    },
    //重置审批
    resetExamine(){
      this.formInfo={};
      this.questions=[];
      this.answers=[];
      this.nodeInst={};
      this.flowInfo={};
      this.handleReset();
    },
    //提交审批
    submitExamine(op){
        //op=0,流程前进，op=2，流程终止，op=3回退
        //检查审核意见
        if(this.nodeInst.idea==''){
            this.$message({
                message:'您尚未填写审批意见',
                type: 'warning'
            });
            return;
        }
        //生成签名base64
        this.handleGenerate();
        //检查签名
        if(this.nodeInst.sign==''){
            return;
        }
        //检查无误，开始发送请求
        var params={
            op:op,
            flowInfo:this.flowInfo,
            nodeInst:this.nodeInst
        };
        console.log(params);
        opFlowInst(params).then((response) => {
            this.$message({
                message:'审批成功',
                type: 'success'
            });
        this.resetExamine();
        this.examineDialog=false;
        this.handleQuery();
        });

    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    // 取消按钮
    cancel() {
      this.flowDialogVis = false;
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 抽屉搜索按钮操作 */
    handleFormQuery() {
      this.$refs["drawer"].validate((valid) => {
        if (valid) {
          var params = {
            id: this.drawer.deptId,
          };
          console.log(params.id);
          queryForm(params).then((response) => {
            this.drawer.formList = response.departmentForm;
            this.drawer.formList.forEach((item) => {
              this.$set(item, "tagsArray", []);
              item.tagsArray = item.tags.split(",");
            });
            console.log(this.drawer.formList);
          });
        } else {
          return false;
        }
      });
    },
    /** 新增审批节点操作 */
    handleAddNode(i) {
      var node = {
        id: nanoid(),
        name: undefined, //节点名
        flowId: this.flowDialog.flowInfo.id,
        order: ++this.flowDialog.flowInfo.nodes,
        last: false,
        relatedUserId: "", //关联该节点的用户
      };
      this.flowDialog.flowNodes.splice(i, 0, node);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
  },
};
</script>
